#!/bin/sh
# Copyright 2008-2015, LastPass, LastPass.com
# ALL RIGHTS RESERVED


function verbose_log
{
  if [ "$VERBOSE" -eq 1 ]; then
    echo "$*" >> /tmp/lpinstallstatus
  fi
}

function get_app_path_by_bundle_id_or_name
{
    local BUNDLEID=$1
    local BUNDLE_NAME=$2
    local BUNDLE_DIR=$( if [[ -d "/Applications/${BUNDLE_NAME}" ]]; then   echo  "/Applications/${BUNDLE_NAME}";   else  mdfind "kMDItemCFBundleIdentifier == \"${BUNDLEID}\"" | awk -v appName="${BUNDLE_NAME}"  ' BEGIN{ default="";  bestResult=""; movedApp=""; } /^\/Applications\//{ bestResult=$0; next; } { movedApp=$0; next; } END{ if (length(bestResult) != 0) { print bestResult; exit; } if (length(movedApp) != 0) { print movedApp; exit; } print default; } '; fi )
    echo "${BUNDLE_DIR}"
}


SCRIPT_DIR=`dirname "$0"`
BUNDLE_CONTENT_DIR="${SCRIPT_DIR}/.."
PLUGINS="${BUNDLE_CONTENT_DIR}/SharedSupport" # This should be  PlugIns but first wee need re-codesign support during installer build for that
PACKAGE_PATH=$1
INSTALL_PATH=$2
INSTALL_VOLUME=$3
EXTRA_PARAMS=$4

# We now allow users to opt out of certain browsers
# accept them as additional params
CMD_SAFARI=1
CMD_CHROME=1
CMD_FIREFOX=1
CMD_OPERA=1

if [ $# -gt 4 ]; then
    CMD_SAFARI=$5
fi
if [ $# -gt 5 ]; then
    CMD_CHROME=$6
fi
if [ $# -gt 6 ]; then
    CMD_FIREFOX=$7
fi
if [ $# -gt 7 ]; then
    CMD_OPERA=$8
fi

# next line will be changed by make_release.sh - Is this a joke? why not a simple runtime param ???
VERBOSE=1

SAFARI_PATH=$(get_app_path_by_bundle_id_or_name com.apple.safari Safari.app)
CHROME_PATH=$(get_app_path_by_bundle_id_or_name com.google.Chrome "Google Chrome.app")
FIREFOX_PATH=$(get_app_path_by_bundle_id_or_name org.mozilla.Firefox FireFox.app)
OPERA_PATH=$(get_app_path_by_bundle_id_or_name com.operasoftware.Opera Opera.app)

DOOPERA=1
DOBINARY=1
KILLSAFARI=0 # Why do you want to kill if not installing anything yet???


verbose_log "Working dir: " $(pwd)
verbose_log "Params: $*"

verbose_log "PLUGINS=$PLUGINS"
verbose_log "PACKAGE_PATH=$PACKAGE_PATH"
verbose_log "INSTALL_PATH=$INSTALL_PATH"
verbose_log "INSTALL_VOLUME=$INSTALL_VOLUME"
verbose_log "EXTRA_PARAMS=$EXTRA_PARAMS"

verbose_log "CMD_SAFARI=$CMD_SAFARI"
verbose_log "CMD_CHROME=$CMD_CHROME"
verbose_log "CMD_FIREFOX=$CMD_FIREFOX"
verbose_log "CMD_OPERA=$CMD_OPERA"

verbose_log "SAFARI_PATH=$SAFARI_PATH"
verbose_log "CHROME_PATH=$CHROME_PATH"
verbose_log "FIREFOX_PATH=$FIREFOX_PATH"
verbose_log "OPERA_PATH=$OPERA_PATH"



if [[ "$CMD_FIREFOX" == "1" && -f "$PLUGINS/lp.xpi" ]]
then
  verbose_log "FOUND : \"$PLUGINS/lp.xpi\""
  verbose_log "KILLING FIREFOX"
  ( /usr/bin/killall firefox-bin || exit 0 )
  ( /usr/bin/killall firefox || exit 0 )
fi
if [[ "$CMD_CHROME" == "1"  ]]
then
  verbose_log "KILLING CHROME"
  ( /usr/bin/killall "Google Chrome" || exit 0 )
  ( /usr/bin/killall "Google Chrome Helper" || exit 0 )
fi
if [[ "$CMD_SAFARI" == "1" && "$KILLSAFARI" == "1" ]]
then
    verbose_log "KILLING SAFARI"
    ( /usr/bin/killall Safari || exit 0 )
fi

verbose_log "SLEEPING 1 sec"
/bin/sleep 1

if [[ "$CMD_FIREFOX" == "1" && -f "$PLUGINS/lp.xpi" ]]
then
  verbose_log "KILLING FIREFOX AGAIN"
  ( /usr/bin/killall -9 firefox-bin || exit 0 )
  ( /usr/bin/killall -9 firefox || exit 0 )
fi
if [[ "$CMD_CHROME" == "1" ]]
then
  verbose_log "KILLING CHROME AGAIN"
  ( /usr/bin/killall -9 "Google Chrome" || exit 0 )
  ( /usr/bin/killall -9 "Google Chrome Helper" || exit 0 )
fi
if [[ "$CMD_SAFARI" == "1" && "$KILLSAFARI" == "1" ]]
then
    verbose_log "KILLING SAFARI AGAIN"
    ( /usr/bin/killall -9 Safari || exit 0 )
fi


verbose_log "home dir is $HOME"
HOMEDIRS="$HOME"
for i in /Users/*
do
if [ "$i" != "$HOME" ]
then
  verbose_log "found additional home dir at $i"
  HOMEDIRS="$HOMEDIRS $i"
fi
done
verbose_log "home dirs are $HOMEDIRS"


verbose_log "### FIREFOX : START ###################################################################"
if [[ "$CMD_FIREFOX" == "1" ]]
then
  verbose_log "firefox extension present, installing"

  for HOMEDIR in $HOMEDIRS
  do
    verbose_log "installing into $HOMEDIR"
    if [ -d "$HOMEDIR/Library/Application Support/Firefox/Profiles" ]
    then
      verbose_log "firefox profiles dir exists"
      for i in "$HOMEDIR/Library/Application Support/Firefox/Profiles"/*
      do
        verbose_log "found firefox profile at $i"
        if [ ! -d "$i/extensions" ]
        then
          mkdir -p "$i/extensions"
          chown "`ls -ld "$i" | awk '{print $3; }'`" "$i/extensions"
        fi
        rm -rf "$i/extensions/support@lastpass.com"
        if [[ -f "$PLUGINS/lp.xpi" && "$CMD_FIREFOX" == "1" ]]
        then
          mkdir -p "$i/extensions/support@lastpass.com"
          #if [ -d "$i/extensions/support@lastpass.com" ]
          #then
            #echo "directory created successfully" >> /tmp/lpinstallstatus
          #fi
          unzip -o "$PLUGINS/lp.xpi" -d "$i/extensions/support@lastpass.com"
          chown -R "`ls -ld "$i" | awk '{print $3; }'`" "$i/extensions/support@lastpass.com"
        fi

        # disable firefox password manager
        if [ -f "$i/prefs.js" ]
        then
          egrep "user_pref\(\"signon.rememberSignons\"," "$i/prefs.js" > /dev/null
          if [ $? = 1 ]
          then
            echo "user_pref(\"signon.rememberSignons\", false);" >> "$i/prefs.js"
          fi
        fi
      done
    fi
  done

  verbose_log "Firefox setting up native messaging."

  mkdir -p /Library/Application\ Support/Mozilla/NativeMessagingHosts/
  rm -rf /Library/Application\ Support/Mozilla/NativeMessagingHosts/nplastpass.app/
  unzip -d /Library/Application\ Support/Mozilla/NativeMessagingHosts/ "$PLUGINS/nplastpass.app.zip"
  echo "{ \
    \"name\": \"com.lastpass.nplastpass\", \
    \"description\": \"LastPass\", \
    \"path\": \"/Library/Application Support/Mozilla/NativeMessagingHosts/nplastpass.app/Contents/MacOS/nplastpass\", \
    \"type\": \"stdio\", \
    \"allowed_extensions\": [ \
      \"support@lastpass.com\", \
      \"lastpass-dogfood@logmein.com\" \
    ] \
  }" > /Library/Application\ Support/Mozilla/NativeMessagingHosts/com.lastpass.nplastpass.json
fi

#
# DO NOT use this if you ever needed to, at least not this way
# search with google how to start UI app in the correct bootstrap and session !!!
#
#for i in `/usr/bin/users`; do
#    sudo -u "$i" /usr/bin/open -a "${FIREFOX_PATH}" # https://lastpass.com/lastpassffx/
#done
verbose_log "### FIREFOX : DONE ###################################################################"



verbose_log "### CHROME : START ###################################################################"
rm -rf /tmp/lptemp
if [[ "$CMD_CHROME" == "1" ]]
then
  verbose_log "Chrome setting up native messaging."

  mkdir -p /Library/Google/Chrome/NativeMessagingHosts/
  rm -rf /Library/Google/Chrome/NativeMessagingHosts/nplastpass.app/
  unzip -d /Library/Google/Chrome/NativeMessagingHosts/ "$PLUGINS/nplastpass.app.zip"
  echo "{ \
    \"name\": \"com.lastpass.nplastpass\", \
    \"description\": \"LastPass\", \
    \"path\": \"/Library/Google/Chrome/NativeMessagingHosts/nplastpass.app/Contents/MacOS/nplastpass\", \
    \"type\": \"stdio\", \
    \"allowed_origins\": [ \
      \"chrome-extension://hdokiejnpimakedhajhdlcegeplioahd/\", \
      \"chrome-extension://debgaelkhoipmbjnhpoblmbacnmmgbeg/\", \
      \"chrome-extension://hnjalnkldgigidggphhmacmimbdlafdo/\", \
      \"chrome-extension://hgnkdfamjgnljokmokheijphenjjhkjc/\", \
      \"chrome-extension://cdplaefimljmechgghpeadpphdmpjhld/\", \
      \"chrome-extension://hiadejpmkaejfnendkealdpgjgbmelem/\"
    ] \
  }" > /Library/Google/Chrome/NativeMessagingHosts/com.lastpass.nplastpass.json

  mkdir -p /Library/Application\ Support/Chromium/NativeMessagingHosts/
  rm -rf /Library/Application\ Support/Chromium/NativeMessagingHosts/nplastpass.app/
  unzip -d /Library/Application\ Support/Chromium/NativeMessagingHosts/ "$PLUGINS/nplastpass.app.zip"
  echo "{ \
    \"name\": \"com.lastpass.nplastpass\", \
    \"description\": \"LastPass\", \
    \"path\": \"/Library/Application Support/Chromium/NativeMessagingHosts/nplastpass.app/Contents/MacOS/nplastpass\", \
    \"type\": \"stdio\", \
    \"allowed_origins\": [ \
      \"chrome-extension://hdokiejnpimakedhajhdlcegeplioahd/\", \
      \"chrome-extension://debgaelkhoipmbjnhpoblmbacnmmgbeg/\", \
      \"chrome-extension://hnjalnkldgigidggphhmacmimbdlafdo/\", \
      \"chrome-extension://hgnkdfamjgnljokmokheijphenjjhkjc/\", \
      \"chrome-extension://cdplaefimljmechgghpeadpphdmpjhld/\", \
      \"chrome-extension://hiadejpmkaejfnendkealdpgjgbmelem/\"
    ] \
  }" > /Library/Application\ Support/Chromium/NativeMessagingHosts/com.lastpass.nplastpass.json

  if [ "$DOBINARY" = "1" ]
  then
    mkdir -p /tmp/lptemp
    unzip -d /tmp/lptemp "$PLUGINS/lpchrome.crx"
  fi
fi


if [ -f "$PLUGINS/nplastpass.zip" ]
then
  if [ "$DOBINARY" = "1" ]
  then
    mkdir -p /tmp/lptemp
    unzip -d /tmp/lptemp "$PLUGINS/nplastpass.zip"
  fi
fi

verbose_log "Checking Chrome."
if [[ "$CMD_CHROME" == "1" ]]
then
  verbose_log "Chrome browser installed."

  for HOMEDIR in $HOMEDIRS
  do
    if [ -d "$HOMEDIR/Library/Application Support/Google/Chrome/Default/Extensions/hdokiejnpimakedhajhdlcegeplioahd" ]
    then
      verbose_log "Found Chrome extension, LASTPASS_ALREADY_INSTALLED"
    fi
  done

  if [[ ! -d "/Library/Application Support/Google/Chrome/External Extensions" ]]
  then
    verbose_log "Creating Extensions directory."
    mkdir -p "/Library/Application Support/Google/Chrome/External Extensions"
  fi

  verbose_log "Installing Chrome Json file."

  echo "{ \"external_update_url\": \"http://clients2.google.com/service/update2/crx\" }" > "/Library/Application Support/Google/Chrome/External Extensions/hdokiejnpimakedhajhdlcegeplioahd.json"
fi
verbose_log "### CHROME : END ###################################################################"



verbose_log "### MISC : START ###################################################################"
# Install file_chooser portion of the safari binary component -- the helper app relies on it.
if [ "$DOBINARY" = "1" ]
then
  if [ -d "/tmp/lptemp" ]
  then
    rm -rf /Library/Internet\ Plug-Ins/nplastpass.plugin
    cp -r /tmp/lptemp/nplastpass.bundle /Library/Internet\ Plug-Ins/nplastpass.plugin
    chmod 755 /Library/Internet\ Plug-Ins/nplastpass.plugin/Contents/Resources/*.app/Contents/MacOS/*

    # Do not install nplastpass
    rm -rf /Library/Internet\ Plug-Ins/nplastpass.plugin/Contents/MacOS
    rm -rf /tmp/lptemp
  fi
fi


if [ "$DOBINARY" = "1" ]
then
  if [ -f "$PLUGINS/LastPassHelper.zip" ]
  then
    verbose_log "Installing Helper App"
    sudo -u "$USER" mkdir -p "/Users/${USER}/Library/Application Support/LastPass/"
    rm -rf ~/Library/Application\ Support/LastPass/LastPassHelper.app
    sudo -u "$USER" unzip "$PLUGINS/LastPassHelper.zip" -d  ~/Library/Application\ Support/LastPass

    # Register
    verbose_log "Registering Helper App"
    if [ -f "$PLUGINS/com.lastpass.LastPassHelper.plist" ]
    then
      verbose_log "Helper App plist found"
      sed -i '' "s|REPLACE_HOME|${HOME}|" "$PLUGINS/com.lastpass.LastPassHelper.plist"
      mkdir ~/Library/LaunchAgents
      if [ "$?" = "0" ]; then
        chown "$USER" ~/Library/LaunchAgents
      fi
      cp "$PLUGINS/com.lastpass.LastPassHelper.plist" ~/Library/LaunchAgents/
      sudo -u "$USER" launchctl unload ~/Library/LaunchAgents/com.lastpass.LastPassHelper.plist > /dev/null
      sudo -u "$USER" launchctl load ~/Library/LaunchAgents/com.lastpass.LastPassHelper.plist
    else
      verbose_log "plist NOT found"
    fi
  fi
fi

# If we have old firefoxes trying to write to this directory,
# they will spin during the login attempt if suid file can't be written.
chown $USER ~/Library/Application\ Support/LastPass

for i in `/usr/bin/users`
do
  # disable safari password manager
  sudo -u "$i" /usr/bin/defaults write ~/Library/Preferences/com.apple.Safari AutoFillPasswords -bool false

  # disable chrome password manager
  sudo -Hu "$i" "$PLUGINS/chrome_json" disablepwmgr

  sudo -u "$i" mkdir -p "/Users/$i/Library/Application Support/LastPass/"
  if [ -f "$PLUGINS/lp.xpi" ]
  then
    sudo -u "$i" echo "$EXTRA_PARAMS" > "/Users/$i/Library/Application Support/LastPass/extra_firefox_params"
    chown "$i" "/Users/$i/Library/Application Support/LastPass/extra_firefox_params"
  fi
done

verbose_log "### MISC : END ###################################################################"



verbose_log "### OPERA : START ###################################################################"
if [[ "$DOOPERA" = "1" && "$CMD_OPERA" == "1" ]]
then
  verbose_log "Installing Opera."

  if [ -d "${OPERA_PATH}" ]
  then
    #
    # DO NOT use this if you ever needed to, at least not this way
    # search with google how to start UI app in the correct bootstrap and session !!!
    #
    #for i in `/usr/bin/users`; do
    #  sudo -u "$i" /usr/bin/open -a "${OPERA_PATH}"  https://lastpass.com/dl/
    #done
    /usr/bin/open -a "${OPERA_PATH}"  https://lastpass.com/dl/
  fi
fi

verbose_log "### OPERA : END ###################################################################"



verbose_log "### SAFARI : START ###################################################################"
rm -rf "/Library/Application Support/LastPass"
VER=`sw_vers -productVersion | awk -F . '{ print $2; }'`
if [[ "$CMD_SAFARI" == "1" ]]
then
  verbose_log "Installing Safari."

  if [[ "$VER" -lt "11" ]]; then
    open -a "${SAFARI_PATH}" -n https://extensions.apple.com/details/?id=com.lastpass.lpsafariextension-N24REP3BMN || exit 0
  else
    open -a "${SAFARI_PATH}" -n https://safari-extensions.apple.com/details/?id=com.lastpass.lpsafariextension-N24REP3BMN || exit 0
  fi
#  rm -f "$PLUGINS/../MacOS/LastPass"
#  rm -rf /tmp/lpinstallsafari
#  mkdir -p /tmp/lpinstallsafari
#  if [ ! -f "$PLUGINS/lastpass.safariextz" -a -f "$PLUGINS/lastpass_safariextz" ]
#  then
#    mv -f "$PLUGINS/lastpass_safariextz" "$PLUGINS/lastpass.safariextz"
#  fi
#  if [ -f "$PLUGINS/lastpass.safariextz" -a -f "$PLUGINS/install_lp.html" ]; then
#
#     # DO NOT use this if you ever needed to, at least not this way
#     # search with google how to start UI app in the correct bootstrap and session !!!
#     #
#     for i in `/usr/bin/users`; do
#        /bin/cp "$PLUGINS/lastpass.safariextz" /tmp/lpinstallsafari/
#        chown "$i" "/tmp/lpinstallsafari/lastpass.safariextz"
#/bin/cp "$PLUGINS/install_lp.html" /tmp/lpinstallsafari/#
#        chown "$i" "/tmp/lpinstallsafari/install_lp.html"
#        chown "$i" "/tmp/lpinstallsafari/"
#        ( sudo -u "$i" /usr/bin/open -a "${SAFARI_PATH}" )
#        sleep 5
#        ( sudo -u "$i" /usr/bin/open -a "${SAFARI_PATH}" /tmp/lpinstallsafari/lastpass.safariextz || exit 0 )
#     done
#  fi
#else
#  ( open -a "${SAFARI_PATH}" -n http://lastpass.com/upgrade.php?safari_installed || exit 0 )
fi
verbose_log "### SAFARI : END ###################################################################"



verbose_log "### ALL DONE ###"
verbose_log ""
verbose_log ""

exit 0;
